package com.imti.mapper;

import com.imti.model.Answer;
import com.imti.model.Quest;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface QuestMapper {
    @Select("SELECT t_question.*,`t_repo`.`name`,`t_repo`.id as rid FROM t_question, question_repo ,t_repo\n" +
            "WHERE question_repo.`question_id`=t_question.`id`AND question_repo.`repo_id`=`t_repo`.`id`AND question_repo.`repo_id`=#{rid}")

    @Results(id = "QuestMap",value = {
            @Result(column = "user_id",property = "userId"),
            @Result(column = "answer_id",property = "answerId"),
            @Result(column = "create_time",property = "createTime")
    })
    List<Quest> findAllQuest(Integer id);

    @Select("<script>SELECT t_repo.*,t_question.* FROM t_repo,t_question,question_repo\n" +
            "     WHERE t_repo.`id`=question_repo.`repo_id`\n" +
            "     AND t_question.`id`=question_repo.`question_id`\n" +
            "     AND t_repo.`id`=#{rid}\n" +
            "<if test=\"type!=null and type!=''\"> AND t_question.`type`=#{type}</if>\n" +
            "<if test=\"title!=null and title!=''\">    AND t_question.`title`LIKE concat( '%',#{title},'%')</if></script>")
    @ResultMap("QuestMap")
    List<Quest> findByQuest(Quest quest);


    /**
     * 保存问题
     * @param quest
     * @return
     */
    @Insert("\n" +
        "INSERT INTO t_question (title,TYPE,answer_id,user_id) VALUES(#{title},#{type},#{answerId},#{userId})\n")
    public int saveQuestion(Quest quest);

    /**
     * 中间表向题库添加题目
     * @param quest
     * @return
     */
    @Insert("INSERT INTO `question_repo`(question_id,repo_id) VALUES (#{id},#{rid})\n")
    public int saveQuestionRepo(Quest quest);

    /**
     * 保存答案信息
     * @param answer
     * @return
     */
    @Insert("\n" +
            "INSERT INTO `t_answer`(question_id,context,correct_flag) VALUES (#{questionId},#{context},#{correctFlag})")
    public int saveAnswer(Answer answer);

    /**
     * 获取问题的答案id
     * @param questionId
     * @return
     */
    @Select("\n" +
            "SELECT GROUP_CONCAT(id) FROM `t_answer` \n" +
            "WHERE question_id=#{qid}\n" +
            "AND correct_flag=\"1\"")
    public String saveQuestionAnswerId(String questionId);

    /**
     * 更新问题答案
     * @param quest
     * @return
     */
    @Update("\n" +
            "UPDATE `t_question` SET answer_id=#{answerId} where id=#{id}")
    public int updateQuestionAnswerId(Quest quest);


    @Select("SELECT MAX(id) FROM t_question")
    public int getMaxQuestionId();
}